package com.example.deptempmanageservice.service;


import com.example.deptempmanageservice.dao.DepartmentMapper;
import com.myprojects.common.pojo.Department;
import com.myprojects.common.pojo.DepartmentExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DepartmentService {

    @Autowired
    DepartmentMapper departmentMapper;

    public List<Department> findAllDepartment(){
        return departmentMapper.selectByExample(null);
    }

    public int deleteByPrimaryKey(Integer id){
        return departmentMapper.deleteByPrimaryKey(id);
    }

    public int deleteLotsByPrimaryKey(List<Integer> idList){
        return departmentMapper.deleteLotsByPrimaryKey(idList);
    }

    public int insertSelective(Department record){
        return departmentMapper.insertSelective(record);
    }

    public List<Department> selectByExample(DepartmentExample example) {
        return departmentMapper.selectByExample(example);
    }

    public List<Department> selectAllDepartment() {
        return departmentMapper.selectByExample(null);
    }

    public Department selectByPrimaryKey(Integer id){
        return departmentMapper.selectByPrimaryKey(id);
    }

    public Boolean checkDepartmentname(String department_name ){
        long iResult = 0;
        DepartmentExample example = new DepartmentExample();
        example.createCriteria().andDepartment_nameLike(department_name);
        try{
            iResult = departmentMapper.countByExample(example);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Boolean bResult = iResult >= 1;//大于1则说明该部门名存在

        return bResult;
    }


    /**
     * 该方法会检查该部门的所有属性是否合法
     * @return 携带错误信息的map，若map.size()>0则说明验证失败
     */
    public Map<String,Object> checkDepartment(Department department, BindingResult result){
        Map<String , Object> errorMap = new HashMap<>();

        //先检查数据格式是否有误
        if (result.hasErrors()){
            List<FieldError> fieldErrors = result.getFieldErrors();
            for (FieldError error : fieldErrors){
                errorMap.put(error.getField(),error.getDefaultMessage());
            }
        }
        //再检查该用户名是否已存在
        if (this.checkDepartmentname(department.getDepartment_name())){
            errorMap.put("department_name","该部门名已存在!");
        }
        //返回errorMap
        return  errorMap;
    }

    public int updateByPrimaryKeySelective(Department record){
        return departmentMapper.updateByPrimaryKeySelective(record);
    }

}
